﻿using RimWorld;
using RimWorld.Planet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UnityEngine;
using Verse;

namespace SZ.Mech
{


    [StaticConstructorOnStartup]
    public class Verb_CastAbilityDragonFly : Verb_CastAbility
    {
        //public static readonly Texture2D TargeterMouseAttachment = ContentFinder<Texture2D>.Get("UI/Overlays/LaunchableMouseAttachment");
        public static readonly Texture2D TargeterMouseAttachment = ContentFinder<Texture2D>.Get("UI/Abilities/SZ_DragonFlyUI");

        //protected override float EffectiveRange
        //{
        //    get
        //    {
        //        return verbProps.range;
        //    }
        //}

        //public List<CompTransporter> TransportersInGroup => Transporter.TransportersInGroup(parent.Map);
        DragonFlyExtension dragonFlyExtension;

        protected override bool TryCastShot()  
        {
            //if (base.TryCastShot())
            // {
                dragonFlyExtension = ability.def.GetModExtension<DragonFlyExtension>();
                if (caster.Faction == Faction.OfPlayer)
                {
                    if (CasterPawn.IsColonyMechPlayerControlled && CasterPawn.Drafted)
                    {
                        StartChoosingDestination();
                    }
                }
                else
                {
                    Messages.Message("太昊盘云而上，呼唤了其他天兵".Translate(), Caster, MessageTypeDefOf.TaskCompletion);
                    IncidentRaid();
                    AIStartChoosingDestination();
                }
            ability.StartCooldown(ability.def.cooldownTicksRange.RandomInRange);

            return true;
           // }
           // return false;
        }
        public int MaxLaunchDistance = 50;


         public void IncidentRaid()
        {
            IncidentParms incidentParms = new IncidentParms();
            incidentParms.target = caster.Map;
            incidentParms.points = StorytellerUtility.DefaultThreatPointsNow(caster.Map);
            //incidentParms.raidArrivalMode = PawnsArrivalModeDefOf.RandomDrop;
            incidentParms.raidArrivalMode = PawnsArrivalModeDefOf.EdgeDrop;
            incidentParms.raidStrategy = RaidStrategyDefOf.ImmediateAttack;
            incidentParms.raidForceOneDowned = true;
            incidentParms.raidNeverFleeIndividual = true;//突袭从不逃跑
            incidentParms.faction = Find.FactionManager.FirstFactionOfDef(SZ_DefOf.SZ_HeavenForgedCelestiall);
            IncidentDefOf.RaidEnemy.Worker.TryExecute(incidentParms);
        }

        public void AIStartChoosingDestination()
        {
            var tile = caster.Map.Tile;
            var map = Find.WorldObjects.WorldObjectAt<MapParent>(tile);
            //RCellFinder.FindSiegePositionFrom()
            //caster.Map
            IntVec3 cell = RandomDropPoint(caster.Position);
            TryLaunch(tile, new TransportPodsArrivalAction_SZLandInSpecificCell(map, cell, dragonFlyExtension.activeDropPodFly, dragonFlyExtension.dropPodIncomingFly));//这里会有个传送到达提示，但可以改
        }

        public IntVec3 RandomDropPoint(IntVec3 lastPoint)
        {
            IntVec3 pos = DropCellFinder.RandomDropSpot(caster.Map);

            if (pos.DistanceTo(lastPoint) < 50)
            {
                pos = RandomDropPoint(lastPoint);
            }
            return pos;
        }

        /// <summary>
        /// 开始发射目的地程序
        /// </summary>
        public void StartChoosingDestination()
        {
            CameraJumper.TryJump(CameraJumper.GetWorldTarget(this.caster));
            Find.WorldSelector.ClearSelection();
            int tile = this.caster.Map.Tile;
            Find.WorldTargeter.BeginTargeting(ChoseWorldTarget, canTargetTiles: true, TargeterMouseAttachment, closeWorldTabWhenFinished: true,
                delegate
                {//这个函数每帧都可以刷新
                    GenDraw.DrawWorldRadiusRing(tile, MaxLaunchDistance);
                }, (GlobalTargetInfo target) => TargetingLabelGetter(target, tile, MaxLaunchDistance, null, TryLaunch));
        }

        public void TryLaunch(int destinationTile, TransportPodsArrivalAction arrivalAction)
        {
            Pawn p = caster as Pawn;
            if (p.drafter != null)
            {
                p.drafter.Drafted = false;
            }
            if (!this.caster.Spawned)
            {
                Log.Error(string.Concat("Tried to launch ", this.caster, ", but it's unspawned."));
                return;
            }
            Map map = caster.Map;

            int num = Find.WorldGrid.TraversalDistanceBetween(map.Tile, destinationTile);
            if (num <= MaxLaunchDistance)
            {
                ActiveDropPod activeDropPod = (ActiveDropPod)ThingMaker.MakeThing(dragonFlyExtension.activeDropPodFly);//行动吊舱
                //ActiveDropPod activeDropPod = (ActiveDropPod)ThingMaker.MakeThing(SZ_DefOf.SZ_DragonFlyA);//行动吊舱
                activeDropPod.Contents = new ActiveDropPodInfo();
                caster.DeSpawn(DestroyMode.Vanish);

                activeDropPod.Contents.innerContainer.TryAddOrTransfer(caster, true);

                //activeDropPod.Contents.innerContainer.TryAdd(caster,true);
                //activeDropPod.Contents.innerContainer.TryAddRangeOrTransfer(new List<Thing> { caster });

                FlyShipLeaving obj = (FlyShipLeaving)SkyfallerMaker.MakeSkyfaller(dragonFlyExtension.dropPodLeavingFly, activeDropPod);//飞行中的效果                                                                                                       //FlyShipLeaving obj = (FlyShipLeaving)SkyfallerMaker.MakeSkyfaller(SZ_DefOf.DropPodLeavingDragonFlyA, activeDropPod);//飞行中的效果
                obj.groupID = Find.UniqueIDsManager.GetNextTransporterGroupID();//可能可以这样写
                obj.destinationTile = destinationTile;
                obj.arrivalAction = arrivalAction;//到达行动
                obj.worldObjectDef = WorldObjectDefOf.TravelingTransportPods;
                //compTransporter.CleanUpLoadingVars(map);
                //compTransporter.parent.Destroy();
                GenSpawn.Spawn(obj, caster.Position, map);
            }
            CameraJumper.TryHideWorld();
        }

        public bool ChoseWorldTarget(GlobalTargetInfo target)
        {
            return ChoseWorldTarget(target, caster.Map.Tile, MaxLaunchDistance, TryLaunch);
        }

        public bool ChoseWorldTarget(GlobalTargetInfo target, int tile, int maxLaunchDistance, Action<int, TransportPodsArrivalAction> launchAction)
        {
            if (!target.IsValid)
            {
                //目标无效
                Messages.Message("MessageTransportPodsDestinationIsInvalid".Translate(), MessageTypeDefOf.RejectInput, historical: false);
                return false;
            }
            int num = Find.WorldGrid.TraversalDistanceBetween(tile, target.Tile);
            if (maxLaunchDistance > 0 && num > maxLaunchDistance)
            {
                //目标距离过远
                Messages.Message("TransportPodDestinationBeyondMaximumRange".Translate(), MessageTypeDefOf.RejectInput, historical: false);
                return false;
            }
            // IEnumerable<FloatMenuOption> source = ((launchable != null) ? launchable.GetTransportPodsFloatMenuOptionsAt(target.Tile) : GetOptionsForTile(target.Tile, pods, launchAction));
            IEnumerable<FloatMenuOption> source = GetTransportPodsFloatMenuOptionsAt(target.Tile);

            if (!source.Any())//如果不能检索到空间，则不发射
            {
                return false;
            }

            //    if (!source.Any())//如果不包含任何命令元素
            //{
            //    if (Find.World.Impassable(target.Tile))
            //    {
            //        Messages.Message("MessageTransportPodsDestinationIsInvalid".Translate(), MessageTypeDefOf.RejectInput, historical: false);
            //        return false;
            //    }
            //    launchAction(target.Tile, null);
            //    return true;
            //}
            if (source.Count() == 1)
            {
                if (!source.First().Disabled)
                {
                    source.First().action();
                    return true;
                }
                return false;
            }
            Find.WindowStack.Add(new FloatMenu(source.ToList()));
            return false;
        }






        public IEnumerable<FloatMenuOption> GetTransportPodsFloatMenuOptionsAt(int tile)
        {
            bool anything = false;
            //if (TransportPodsArrivalAction_FormCaravan.CanFormCaravanAt(TransportersInGroup.Cast<IThingHolder>(), tile) && !Find.WorldObjects.AnySettlementBaseAt(tile) && !Find.WorldObjects.AnySiteAt(tile))
            //{
            //    anything = true;
            //    yield return new FloatMenuOption("FormCaravanHere".Translate(), delegate//在这里组建大篷车
            //    {
            //        TryLaunch(tile, new TransportPodsArrivalAction_FormCaravan());
            //    });
            //}
            List<WorldObject> worldObjects = Find.WorldObjects.AllWorldObjects;
            for (int i = 0; i < worldObjects.Count; i++)
            {
                if (worldObjects[i].Tile != tile)
                {
                    continue;
                }
                else
                {
                    //if(worldObjects[i] is Settlement)
                    //{

                    //}
                    if (worldObjects[i] is MapParent mapParent)
                    {
                        if (mapParent.HasMap)
                        {
                            yield return GetTransportPodsFloatMenuOptions(tile, mapParent);
                            anything = true;
                        }
                    }
                }

                //foreach (FloatMenuOption transportPodsFloatMenuOption in worldObjects[i].GetTransportPodsFloatMenuOptions(null, this))
                //{
                //    anything = true;
                //    yield return transportPodsFloatMenuOption;
                //}
            }
            //只需要可显示的地图传送。
            //if (!anything && !Find.World.Impassable(tile))
            //{
            //    //如果不包含任何地块元素，则内容物将丢失
            //    yield return new FloatMenuOption("TransportPodsContentsWillBeLost".Translate(), delegate
            //    {
            //        TryLaunch(tile, null);
            //    });
            //}
        }

        public FloatMenuOption GetTransportPodsFloatMenuOptions(int tile, MapParent mapParent)
        {
            return new FloatMenuOption("LandInExistingMap".Translate(mapParent.Label), delegate
           {



               Map myMap = caster.Map;
               Map map = mapParent.Map;
               Current.Game.CurrentMap = map;
               CameraJumper.TryHideWorld();
               Find.Targeter.BeginTargeting(TargetingParameters.ForDropPodsDestination(), delegate (LocalTargetInfo x)//地块传送选择
               {
                   TryLaunch(tile, new TransportPodsArrivalAction_SZLandInSpecificCell(mapParent, x.Cell, dragonFlyExtension.activeDropPodFly, dragonFlyExtension.dropPodIncomingFly));
                   //TryLaunch(tile, new TransportPodsArrivalAction_LandInSpecificCell(mapParent, x.Cell, false));
                   //representative.TryLaunch(base.Tile, new TransportPodsArrivalAction_LandInSpecificCell(this, x.Cell, representative.parent.TryGetComp<CompShuttle>() != null));
               }, null, delegate
               {
                   if (Find.Maps.Contains(myMap))
                   {
                       Current.Game.CurrentMap = myMap;
                   }
               }, CompLaunchable.TargeterMouseAttachment);
           });
        }


        //public static IEnumerable<FloatMenuOption> GetOptionsForTile(int tile, Action<int, TransportPodsArrivalAction> launchAction)
        //{
        //    bool anything = false;
        //    //if (TransportPodsArrivalAction_FormCaravan.CanFormCaravanAt(pods, tile) && !Find.WorldObjects.AnySettlementBaseAt(tile) && !Find.WorldObjects.AnySiteAt(tile))
        //    //{
        //    //    anything = true;
        //    //    yield return new FloatMenuOption("FormCaravanHere".Translate(), delegate
        //    //    {
        //    //        launchAction(tile, new TransportPodsArrivalAction_FormCaravan("MessageShuttleArrived"));
        //    //    });
        //    //}
        //    //List<WorldObject> worldObjects = Find.WorldObjects.AllWorldObjects;
        //    //for (int i = 0; i < worldObjects.Count; i++)
        //    //{
        //    //    if (worldObjects[i].Tile != tile)
        //    //    {
        //    //        continue;
        //    //    }
        //    //    foreach (FloatMenuOption shuttleFloatMenuOption in worldObjects[i].GetShuttleFloatMenuOptions(pods, launchAction))//获得穿梭器浮动选项
        //    //    {
        //    //        anything = true;
        //    //        yield return shuttleFloatMenuOption;
        //    //    }
        //    //}
        //    if (!anything && !Find.World.Impassable(tile))//不可通行
        //    {
        //        yield return new FloatMenuOption("TransportPodsContentsWillBeLost".Translate(), delegate
        //        {
        //            launchAction(tile, null);
        //        });
        //    }
        //}

        /// <summary>
        /// 显示前往的标签设定
        /// </summary>
        /// <param name="target"></param>
        /// <param name="tile"></param>
        /// <param name="maxLaunchDistance"></param>
        /// <param name="pods"></param>
        /// <param name="launchAction"></param>
        /// <returns></returns>
        public static string TargetingLabelGetter(GlobalTargetInfo target, int tile, int maxLaunchDistance, IEnumerable<IThingHolder> pods, Action<int, TransportPodsArrivalAction> launchAction)
        {
            if (target.WorldObject is MapParent mapParent)
            {
                if (mapParent.HasMap)
                {
                    return "ClickToSeeAvailableOrders_WorldObject".Translate(mapParent.LabelCap);
                }
            }
            return "无效";
        }

    }
}
